//
//  SSComposeViewController.swift
//  SSSina
//
//  Created by ss on 2017/7/10.
//  Copyright © 2017年 ss. All rights reserved.
//

import UIKit

import UIKit

class SSComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        setupNav()
        // 添加控件
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(bottomView)
        // 添加约束
        textView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(view)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: SSSCREENW - 20, height: SSSCREENW - 20))
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(35)
        }
        
        
        // 02 闭包的实例化
        bottomView.closure = {[weak self](type)->() in
            // 04 闭包回调
            
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .add:
                print("+")
            }
        }
        
        // 监听配图中加号图片点击
        // 02 04
        pictureView.closure = {[weak self] in
            self?.selectImage()
        }
        
        // 监听系统通知监听键盘
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    //MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        // 默认不能点击
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        navigationItem.titleView = titleView
    }
    
    //MARK: - 懒加载控件
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(sendClick), for: UIControlEvents.touchUpInside)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: UIControlState.disabled)
        button.setTitle("发送", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: SSNormalFontSize)
        button.frame.size = CGSize(width: 50, height: 35)
        return button
    }()
    // titleView
    private lazy var titleView: UILabel = {
        // 获取名字
        let name = SSOAuthViewModel.share.userAccountModel?.screen_name ?? ""
        // 最终要显示的文字
        let str = "发微博\n\(name)"
        // 范围
        let range = (str as NSString).range(of: name)
        // 通过字符串获取富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本属性
        attr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: SSThemeColor], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.textAlignment = .center
        lab.sizeToFit()
        return lab
    }()
    // 自定义textView
    fileprivate lazy var textView: SSComposeTextView = {
        let view = SSComposeTextView()
        view.placeholder = "ss新浪微博"
        //        let txt = UITextField()
        ////        txt.placeholder
        //        view.placeholder
        view.delegate = self
        view.font = UIFont.systemFont(ofSize: 16)
        // 上下滚动
        view.alwaysBounceVertical = true
        return view
    }()
    // 底部视图
    fileprivate lazy var bottomView: SSComposeBottomView = SSComposeBottomView()
    
    // 自定义配图
    fileprivate lazy var pictureView: SSComposePictureView = SSComposePictureView()
    
    // 自定义表情键盘
    fileprivate lazy var keyboardView: SSEmoticonKeyboardView = SSEmoticonKeyboardView()
}
//MARK: - 底部视图按钮点击事件监听
extension SSComposeViewController{
    fileprivate func selectImage(){
        // 打开相册
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        // 是否可以编辑
        //        pickerVc.allowsEditing = true
        // 判断是否可以打开相机 或者相册
        //        UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType)
        // 判断前后摄像头是否可用
        //        UIImagePickerController.isFlashAvailable(for: UIImagePickerControllerCameraDevice.front)
        self.present(pickerVc, animated: true, completion: nil)
    }
    
    // 切换键盘
    func switchKeyboard(){
        // inputView
        // self.textView.inputView == nil 就代表的是系统键盘 反之是表情键盘
        //        if self.textView.inputView == nil {
        //            self.textView.inputView = keyboardView
        //        }else{
        //            self.textView.inputView = nil
        //        }
        self.textView.inputView = (self.textView.inputView == nil ? keyboardView : nil)
        // 赋值
        self.bottomView.isEmoticon = (self.textView.inputView != nil)
        // 刷新inputView
        self.textView.reloadInputViews()
        // 开启第一响应者
        self.textView.becomeFirstResponder()
    }
}
//MARK: - UIImagePickerControllerDelegate
extension SSComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        // 通过key 获取image
        guard  let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else{
            return
        }
        //
        //        let i = dealImageScale(image: image, maxWidth: 400)
        //
        //        let data = UIImagePNGRepresentation(i)!
        //
        //        // 转成nsdata
        //        let nsData = NSData.init(data: data)
        //        nsData.write(toFile: "/Users/xiele/Desktop/haha1.png", atomically: true)
        
        // 赋值
        pictureView.addImage(image: image.dealImageScale(maxWidth: 400))
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    
}


//MARK: - UITextViewDelegate
extension SSComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 取消第一响应者
        self.textView.resignFirstResponder()
    }
}

//MARK: - 监听事件
extension SSComposeViewController{
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendClick(){
        print("发送按钮点击")
    }
}
//MARK: - 监听通知方法
extension SSComposeViewController{
    // 监听键盘frame变化
    @objc fileprivate func keyboardWillChangeFrame(noti: Notification){
        
        // 判断是否为nil
        guard let userInfo = noti.userInfo else {
            return
        }
        // 获取rect NSRect (NSValue) CGRect
        let rect = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        // 获取动画时长
        let durating = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        // 更新底部视图的底部约束
        self.bottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(rect.origin.y - SSSCREENH)
        }
        // 设置动画
        UIView.animate(withDuration: durating) {
            self.view.layoutIfNeeded()
        }
        
    }
}
